<?php
namespace app\controller;

use think\Request;
use think\facade\Env;
use think\helper\Str;

use OSS\OssClient;
use OSS\Core\OssException;

class Browse extends Common
{
	function index(Request $request) {
		$id = $request->param('id', '', 'trim');
		if( empty($id) ) {
			return response("站点源码未上传, 初始化失败！", 200);
		}
		
		$indexDirectory = public_path('storage') . 'edit' . DIRECTORY_SEPARATOR . $id . DIRECTORY_SEPARATOR . 'index.html';
		if(!file_exists($indexDirectory)) {
			return response("站点源码未上传, 初始化失败", 200);
		}

		return response(file_get_contents($indexDirectory), 200);
	}

	/**
	 * 上传二维码
	 *
	 * @return
	 */
	public function upload(Request $request)
	{
		$files = $request->file();
		if (!isset($files['upload'])) {
			return json(['uploaded'=> 0, 'message'=> '上传失败!', 'url'=> null]);
		}
		if(!is_object($files['upload'])) {
			return json(['uploaded'=> 0, 'message'=> '上传失败!', 'url'=> null]);
		}
		$object = 'edit' . '/' . md5( Str::random(32) . mt_rand(10000, 999999) ) . '.' . $files['upload']->getOriginalExtension();
		$array = $this->uploadFile($object, $files['upload']->getPathName());
		return json($array);
	}

	/**
	 * 上传方法
	 *
	 * @return
	 */
	protected function uploadFile($object, $filePath)	{
		$result = ['uploaded'=> 0, 'message'=> '上传失败!', 'url'=> null];
		if (file_exists($filePath) == false) {
			return $result;
		}
		$bucket = Env::get('aliyun.bucket', 'bucket');
		if ($bucket == 'bucket') {
			return $result;
		}
		$endpoint = Env::get('aliyun.endpoint', 'endpoint');
		if ($endpoint == 'endpoint') {
			return $result;
		}
		$accessKeyId = Env::get('aliyun.accesskeyid', 'accesskeyid');
		if ($accessKeyId == 'accessKeyId') {
			return $result;
		}
		$accessKeySecret = Env::get('aliyun.accesskeysecret', 'accesskeysecret');
		if ($accessKeySecret == 'accessKeySecret') {
			return $result;
		}
		$originaldomain = Env::get('aliyun.originaldomain', 'originaldomain');
		if ($originaldomain == 'originaldomain') {
			return $result;
		}
		$domain = Env::get('aliyun.domain', 'domain');
		if ($domain == 'domain') {
			return $result;
		}
		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
				$result = ['uploaded'=> 1, 'message'=> '上传成功!', 'url' => str_replace($originaldomain, $domain, $result['info']['url'])];
			}
		} catch (OssException $e) {
			$result = ['uploaded'=> 0, 'message'=>$e->getMessage(), 'url'=> null];
		}
		return $result;
	}

}
